import akka.actor.{Actor, ActorSystem, Props}
import akka.event.Logging
import akka.util.Timeout
import akka.pattern.ask

import scala.concurrent.duration._
import scala.sys.process._
import scala.util.{Failure, Success}
import scala.concurrent.ExecutionContext.Implicits.global

object TestShell {

  class PingActor extends Actor {
    override def receive: Receive = {
      case ip: String => sender() ! ping(ip)
      case _ => println("undefined type !")
    }
  }

  class PingAllActor extends Actor {
    val log = Logging(context.system, this)

    override def receive: Receive = {
      case "begin" => {
        val ips = Range(1, 25).map(s"192.168.1." + _)
        implicit val timeout = Timeout(200 seconds)
        ips.foreach(ip => {
//          println("create actor by " + ip)
          val future = context.actorOf(Props[PingActor]) ? ip
          future.onComplete {
            case Success(v) => log.info(s"$ip onSuccess v=$v")
            case Failure(e) => log.info(s"$ip onFailure e=${e.getMessage}")
          }
        })

//        for (ip <- ips){
//          log.info("create actor by " + ip)
//          val future = context.actorOf(Props[PingActor], name = ip) ? ip
//          future.onComplete {
//            case Success(v) => log.info(s"$ip onSuccess v=$v")
//            case Failure(e) => log.info(s"$ip onFailure e=${e.getMessage}")
//          }
//        }

      }
    }
  }

  def ping(ip: String = "127.0.0.1"): (Boolean, String) = {
    try {
      val out = Seq("ping", "-c", "5", "-s", "1024", ip).!!
//      println(s"ping $ip : $out")
      (true, out.split("\n").last)
    } catch {
      case e: Exception => (false, e.getMessage)
    }
  }

  def main(args: Array[String]): Unit = {
    ActorSystem("pingActor").actorOf(Props[PingAllActor]) ! "begin"
//    println(ping("192.168.1.189"))
  }
}
